<template>
  <jc-bar prve-btn @prve="() => $router.go(-1)">
    <v-spacer></v-spacer>
  </jc-bar>
      <div class="mx-auto mt-36 p-6  max-w-[380px]  border  rounded-xl shadow-lg"    >

        <div class=" mb-4 w-full justify-start flex items-center">
          <img class="w-10 h-10" :src="DengTanPng" />
          <div class=" text-xl ml-2 text-title" >{{ title }}</div>
        </div>
        <div>
          <v-form ref="form" lazy-validation  >
            <v-text-field v-model="formData.email" :rules="[rules.required]" label="邮箱"
              name="email"></v-text-field>

            <v-text-field v-model="formData.password" :rules="[rules.required]" type="password" :label="passwordLabel"
              name="password"></v-text-field>

              <v-text-field v-if="isRegister" v-model="formData.confirmPassword" :rules="[rules.required]" type="password" label="确认密码"
              name="confirmPassword"></v-text-field>
              <div class="flex w-full items-center">
                <div class="mr-2 flex-1" >
                  <v-text-field  v-model="formData.code" :rules="[rules.required]" filled clearable
                  label="验证码"
                  name="code"></v-text-field>
                </div>
                <img v-if=" isLogin || isRegister"  class="w-24 h-full mb-2" :src="`data:image/gif;base64,${codeImg}`" @click="getCodeImg"></img>
                <v-btn v-if="isForget" @click="getForgetCode">获取验证码</v-btn>
            </div>
          </v-form>
          <div>

            <v-btn style="width: 320px;" class="my-4" color="primary"  @click="submit">
              {{ btnText }}
            </v-btn>
          </div >
            <div class="flex justify-between w-full">
              <v-btn variant="text" color="orange-darken-1" @click="toHome">回首页</v-btn>
              <v-btn v-if="!isForget" variant="text"  @click="toForget" >忘记密码?</v-btn>
              <v-btn variant="text"  @click="toLogin" > {{ jumpText }} </v-btn>
            </div>
       </div>
    </div>
</template>
<script lang="ts">
import DengTanPng from '@/assets/dengta.png'
import BackageContainer from '@/layout/BackageContainer.vue'
import { mapActions } from 'vuex'
import { getCaptchaImage,register ,sendForgetCode,forgetPassword} from '@/api/cloudbase-login.js'
import JcBar from "@/layout/JcBar.vue";


enum PageTypeEnum {
  Register = 'Register',
  Login = 'Login',
  Forget = 'Forget'
}


export default {
  name: 'Login',
  components: { JcBar, BackageContainer },
  computed:{

    pageType(){
      return this.$route.name as PageTypeEnum
    },

    isLogin(){
      return this.$route.name === PageTypeEnum.Login
    },

    isRegister(){
      return this.$route.name === PageTypeEnum.Register
    },
    isForget(){
      return this.$route.name === PageTypeEnum.Forget
    },
    title(){
      return this.$route.meta.title
    },
    btnText(){

      switch(this.pageType){
        case PageTypeEnum.Login:
        return '登陆'
        case PageTypeEnum.Register:
          return '注册'
        default:
          return '提交'
      }

    },
    passwordLabel(){
      switch(this.pageType){
        case PageTypeEnum.Forget:
        return '新密码'
        case PageTypeEnum.Register:
          return '密码'

      }
    },
    jumpText(){
      switch(this.pageType){
        case PageTypeEnum.Login:
        return '注册账号'
        default:
          return '登录账号'
      }
    }
  },
  data () {
    return {
      rules: {
        required: (value:string) => !!value || '必填项',
        min: (v:string) => v.length >= 8 || 'Min 8 characters',
      },
      formData: {
        email:'',
        password: '',
      },
      codeImg: '',
      DengTanPng,

    }
  },
  mounted () {
    this.getCodeImg()

  },

  methods: {
    ...mapActions("login", ["login"]),

    toReg () {
      this.$router.push('/register')
    },
    async getCodeImg () {
      try {
        const res = await getCaptchaImage()
        this.codeImg = res.img
        this.formData.uuid = res.uuid
      } catch (error) {
        console.log("获取验证码错误-->", error)
      }
    },
    toLogin () {
      this.$refs.form.reset()
      if(this.isRegister || this.isForget){
        this.$router.replace("/login")
      }else{
        this.$router.replace("/register")
      }
      },

      async submitReg () {
        const valid = this.$refs.form.validate()
        if (!valid) {
          return
        }

        if(this.formData.confirmPassword != this.formData.password){
          this.$toast.error("两次密码输入不一致")
          return;
        }

        console.log("注册账号",this.formData)
        try {
          this.formData.registerTerminal = 0
          await register(this.formData)
          this.$toast.success("注册成功，请在邮箱中查看激活码，\n点击进行账号激活！")
          // this.$refs.form.reset()
          this.toMemberValidate()
        } catch (error) {

        }finally{
          this.getCodeImg()
        }
    },
    async submit () {
      if(this.isRegister){
        this.submitReg()
        return;
      }



      const valid = this.$refs.form.validate()
      if (!valid) {
        return
      }

      if(this.isForget){
        forgetPassword(this.formData).then(()=>{
          this.$toast.success("密码修改成功")
          this.$router.replace("/login")
        })
        return;
      }
      try {

        await this.login(this.formData)
        const redirect = this.$route.query.redirect
        if(redirect){
          this.$router.replace(redirect)
        }else{
          this.$router.replace({
            name:'star-home'
          })
        }
      } catch (error) {

      }finally{
        this.getCodeImg()
      }
    },
    toHome(){
      this.$router.replace('/home')
    },
    toMemberValidate(){
      this.$router.push({
        name:'MemberValidate',
        query:{
          email:this.formData.email,
        }
      })
    },
    toForget(){
      this.$router.replace('/forget_password')
    },

    getForgetCode(){
      if(!this.formData.email){
        this.$toast.error("请输入邮箱")
        return;
      }
      sendForgetCode({email:this.formData.email}).then((res)=>{
        this.$toast.success("验证码已发到邮箱\n请注意检查邮件")
      })
    }
  }
}
</script>



<style scoped>
.t-container {
  width: 100%;
  height: 100%;
  background-color: purple;
}

.btn {
  width: 190px;
  height: 69px !important;
  font-size: 28px;
  font-weight: 800;
  color: #fff;
  /* text-shadow: 3px 3px 1px black; */
  animation: shadow 2s ease-in var(--index) infinite;
}

@keyframes shadow {

  0%,
  100% {
    text-shadow: 0px 0px 1px black;
  }

  50% {
    text-shadow: 5px 5px 6px black;
  }
}

.back-btn {
  position: absolute;
  left: 10px;
  top: 10px;
}

.input-key-container {
  position: absolute;
  top: 30px;
  margin: 0 auto;
  height: 80px;
  width: 230px;
}

.chip {
  position: absolute;
  top: 70px;
  left: 0px;
  right: 0px;
  padding: 0 20px;
  color: #ffffff;
}

.header {
  position: fixed;
  top: 6px;
  width: 100%;
  display: flex;
  justify-content: end;
  column-gap: 10px;
  padding: 0 10px;
}

.code-card {
  margin-top: 200px;
  transition: margin-top 0.5s ease-in-out;
}



@media (max-width: 768px) {
  .code-card:has(.v-input--is-focused) {
    margin-top: 80px;
  }
}
</style>
